package shuaige.jdk.多线程.锁.可重入锁_synchronized;

public class Synchronized_线程同步 {
    public static void main(String[] args) throws Exception {
        var add = new AddThread_Synchronized_线程同步();
        var dec = new DecThread_Synchronized_线程同步();
        add.start();
        dec.start();
        add.join();
        dec.join();
        System.out.println(Counter_Synchronized_线程同步.count);
    }
}

class Counter_Synchronized_线程同步 {
    public static final Object lock = new Object();
    public static int count = 0;
}

class AddThread_Synchronized_线程同步 extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            synchronized (Counter_Synchronized_线程同步.lock) {
                Counter_Synchronized_线程同步.count += 1;
            }
        }
    }
}

class DecThread_Synchronized_线程同步 extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            synchronized (Counter_Synchronized_线程同步.lock) {
                Counter_Synchronized_线程同步.count -= 1;
            }
        }
    }
}